import { useMemberStore } from '@/stores'

const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'

const memberStore = useMemberStore()

// 添加拦截器
const httpInterceptor: UniApp.InterceptorOptions = {
  invoke(options: UniApp.RequestOptions) {
    if (!options.url.startsWith('http')) {
      options.url = baseURL + options.url
    }
    options.timeout = 10000
    options.header = {
      ...options.header,
      'source-client': 'miniapp'
    }
    const token = memberStore.profile?.token
    if (token) {
      options.header['Authorization'] = token
    }
    console.log('options', options)
  }
}

// 拦截 reuqest 请求
// 拦截 uploadFile 请求
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

interface Data<T> {
  code: string
  msg: string
  result: T
}

const request = function <T>(
  url: UniApp.RequestOptions['url'],
  data?: UniApp.RequestOptions['data'],
  method: UniApp.RequestOptions['method'] = 'GET',
  options?: UniApp.RequestOptions
) {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      url,
      data,
      method,
      ...options,
      success: res => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data as Data<T>)
        } else if (res.statusCode === 401) {
          // 401 错误 -> 清除用户信息，跳转到登录页
          const memberStore = useMemberStore()
          memberStore.clearProfile() // 清空用户信息
          uni.navigateTo({ url: 'pages/login/login' }) // 跳转到登录页
          reject(res)
        } else {
          uni.showToast({
            icon: 'none',
            title: (res.data as Data<T>).msg || '请求失败'
          })
          reject(res)
        }
      },
      fail: err => {
        uni.showToast({
          icon: 'none',
          title: '网络错误，请换个网络重试'
        })
        reject(err)
      }
    })
  })
}

export const http = {
  get: <T>(
    url: UniApp.RequestOptions['url'],
    data?: UniApp.RequestOptions['data'],
    options?: UniApp.RequestOptions
  ) => request<T>(url, data, 'GET', options),
  post: <T>(
    url: UniApp.RequestOptions['url'],
    data?: UniApp.RequestOptions['data'],
    options?: UniApp.RequestOptions
  ) => request<T>(url, data, 'POST', options),
  put: <T>(
    url: UniApp.RequestOptions['url'],
    data?: UniApp.RequestOptions['data'],
    options?: UniApp.RequestOptions
  ) => request<T>(url, data, 'PUT', options),
  del: <T>(
    url: UniApp.RequestOptions['url'],
    data?: UniApp.RequestOptions['data'],
    options?: UniApp.RequestOptions
  ) => request<T>(url, data, 'DELETE', options)
}
